<?php
namespace control;
//财务归档
use DateInterval;
use DatePeriod;
use DateTime;

class checkoutFilingClass extends adIndexClass
{
    private const page = 'checkoutFiling'; # 权限
    private const table = 'voucher_archive'; # 数据表
    private const tableMx = 'account_elect_file'; # 数据表
    private const title = '归档';
    private string $folderId;

    /*入口页*/
    public function home()
    {

        $date = $this->get('date');
        $leftHtml = <<<EOT
        <div id="work-report-box"></div>
        <script>
        function replaceRightDetail(date){
            let api = root + 'control/adIndex.html?cla={$this->get('cla')}&fun=homeRight'
            $.post(api, { date: date}, function (data) {
                $('#container-detail').html(data.html)
            }, "json");
        }
          laydate.render({
                    elem: '#work-report-box',
                    theme: 'default',
                    format: "yyyy-MM",
                    calendar: true,
                    type: 'month',
                    value: '$date',
                    ready: function(date){
                        let now = date.year+'-'+date.month;
                        return replaceRightDetail(now);
                    },
                    done: function(value){
                        return replaceRightDetail(value);
                    },
                    showBottom: false,
                    position: 'static'
            });
        </script>
EOT;
        $html = <<<EOT
        <div class="box-list">
            <div class="box-left" id="container-left">
                <input name="hideDate" type="hidden" value="{$date}">
                {$leftHtml}
            </div>
            <div class="box-right" id="container-detail">
            </div>
        </div>

EOT;
        //返回
        return $this->homeFun($html);
    }


    public function homeRight()
    {
        $date = $this->post('date') ? $this->post('date') . '-01' : $this->date;
        return $this->detail($date);
    }

    /**
     * 归档
     * @return string
     */
    public function archive(): string
    {
        $html = $this->layerEdit([
                "table" => [
                    [
                        must . '提示' => "是否确认归档？",
                    ],
                ], 'hidden' => hidden(array('name' => 'date', 'value' => $this->post('date'))),
            ]
        );
        //返回
        return $this->layer(array("title" => "编辑", "height" => 200, "html" => $html));
    }

    /*归档-异步处理*/
    public function archiveEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $date = $this->post('date');
        //判断
        if (!$this->power(self::page, "archive")) {
            $json['warn'] = "你没有归档的权限";
        } elseif (empty($this->post('date'))) {
            $json['warn'] = '未找到日期';
        } else {
            $json['warn'] = '新增成功';
            $this->startTrans();
            $where = " coid = '" . self::$coid . "' and locationDate = '$date' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = [
                    'id' => $id,
                    'coid' => self::$coid,
                    'month' => date('Y-m', strtotime($date)),
                    'locationDate' => $date,
                    'stid' => self::$stid,
                    'time' => $this->time
                ];
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $id = $info['id'];
            }
            delete(array('table' => self::tableMx, 'where' => "targetId = '$id' and targetId !='' and coid = '" . self::$coid . "'"));
            $company = query('company',"coid = '".self::$coid."'");
            //判断是否生成了文件夹
            $parent_file = query('account_elect_file', "coid = '" . self::$coid . "' and type = 'folder' and name = '财务归档' and pid = '1'");
            $account_elect_file = query('account_elect_file', "coid = '" . self::$coid . "' and type = 'folder' and name = '$company[name]' and pid = '$parent_file[id]'");
            $this->folderId  = $account_elect_file['id'];
            $saveDir = 'financeArchive/'.$company['name'];
            $url = 'file/' . $saveDir . "/" . date("Ym", strtotime($date));
            $this->_mkdir($url);
            //生成明细账
            $bool = $this->generateDetail($id, $date, $url);
            if (!$bool) {
                $json['warn'] = $bool;
            }

            //生成凭证
            $bool = $this->generateVoucher($id, $date, $url);
            if (!$bool) {
                $json['warn'] = $bool;
            }
            //资产负债表
            $bool = $this->generateAssetDebt($id, $date, $url);
            if (!$bool) {
                $json['warn'] = $bool;
            }
            //利润表
            $bool = $this->generateProfit($id, $date, $url);
            if (!$bool) {
                $json['warn'] = $bool;
            }
            //现金流量表
            $bool = $this->generateCash($id, $date, $url);
            if (!$bool) {
                $json['warn'] = $bool;
            }
            //核算项目明细账
            $bool = $this->generateProjectDetail($id, $date, $url);
            if (!$bool) {
                $json['warn'] = $bool;
            }
            //核算项目余额
            $bool = $this->generateProjectBalance($id, $date, $url);
            if (!$bool) {
                $json['warn'] = $bool;
            }
            //余额表
            $bool = $this->generateSubjectBalance($id, $date, $url);
            if (!$bool) {
                $json['warn'] = $bool;
            }
            //总账
            $bool = $this->generateTotalAccount($id, $date, $url);
            if (!$bool) {
                $json['warn'] = $bool;
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '归档成功';
                $json['warn'] = 2;
                $json['href'] = $this->root . 'control/adIndex.html?cla=' . self::page . '&fun=home&date=' . date('Y-m', strtotime($date));
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 核算项目余额表
     * @param $id
     * @param $date
     * @param $url
     * @return bool|string
     */
    public function generateProjectBalance($id, $date, $url): bool|string
    {
        $company = query('company',"coid = '".self::$coid."'");
        $fileName = $company['name'].'_'.date('Y-m', strtotime($date)) . '月核算项目余额表.xlsx';
        $bool = $this->exportFile_project_balance(serverRoot . $url . '/' . $fileName, $fileName, date('Y-m', strtotime($date)));
        if ($bool) {
            $bool = static::insert(array(
                'table' => self::tableMx,
                'field' => [
                    'id' => suiji(),
                    'targetId' => $id,
                    'coid' => self::$coid,
                    'pid' => $this->folderId,
                    'type' => 'file',
                    'name' => $fileName,
                    'path' => $url . '/' . $fileName,
                    'size' => filesize(serverRoot . $url . '/' . $fileName),
                    'suffix' => 'xlsx',
                    'stid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                return '生成核算项目余额表失败';
            }
        }
        return true;
    }

    public function exportFile_project_balance($saveDir, $fileName, $month): bool
    {
        $title = array("辅助核算编码", "辅助核算名称", "借方期初余额", "贷方期初余额", '借方本期发生额', '贷方本期发生额', '借方期末余额', '贷方期末余额');
        $tr = [];
        $obj = new projectBalanceClass();
        $option = ['客户', '供应商', '员工', '部门', '存货', '项目', '现金流'];
        $where = "a.coid = '" . self::$coid . "' and a.isTemplate = '否' and date_format(a.recordDate,'%Y-%m') = '$month'".voucherClass::joinWhere();
        foreach ($option as $workFlow) {
            $all = match ($workFlow) {
                '客户' => find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId join subject as c on b.subjectId = c.id", 'field' => "distinct subjectId,khid", "where" => $where . " and khid !='' order by any_value(c.code) asc")),
                '供应商' => find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId join subject as c on b.subjectId = c.id", 'field' => "distinct subjectId,supplierId", "where" => $where . " and supplierId !='' order by any_value(c.code) asc")),
                '员工' => find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId join subject as c on b.subjectId = c.id", 'field' => "distinct subjectId,staffId", "where" => $where . " and staffId !='' order by any_value(c.code) asc")),
                '部门' => find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId join subject as c on b.subjectId = c.id", 'field' => "distinct subjectId,departmentId", "where" => $where . " and departmentId !='' order by any_value(c.code) asc")),
                '存货' => find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId join subject as c on b.subjectId = c.id", 'field' => "distinct subjectId,materialId", "where" => $where . " and materialId !='' order by any_value(c.code) asc")),
                '现金流' => find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId join subject as c on b.subjectId = c.id", 'field' => "distinct subjectId,cashId", "where" => $where . " and cashId !='' order by any_value(c.code) asc")),
                '项目' => find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId join subject as c on b.subjectId = c.id", 'field' => "distinct subjectId,projectId", "where" => $where . " and projectId !='' order by any_value(c.code) asc")),
            };
            foreach ($all['array'] as $array) {
                switch ($workFlow) {
                    case '客户':
                        $kehu = query('kehu', "khid = '$array[khid]'");
                        $orderNo = $kehu['orderNo'];
                        $companyName = $kehu['companyName'];
                        break;
                    case '供应商':
                        $supplier = query('supplier', "id = '$array[supplierId]'");
                        $orderNo = $supplier['code'];
                        $companyName = $supplier['name'];
                        break;
                    case '项目':
                        $project = query('project', "id = '$array[projectId]'");
                        $orderNo = $project['orderNo'];
                        $companyName = $project['name'];
                        break;
                    case '存货':
                        $material = query('material', "id = '$array[materialId]'");
                        $orderNo = $material['code'];
                        $companyName = $material['name'] . '-' . $material['model'];
                        break;
                    case '现金流':
                        $cash = query('cash', "id = '$array[cashId]'");
                        $orderNo = $cash['orderNo'];
                        $companyName = $cash['name'];
                        break;
                    case '部门':
                        $department = query('department', "id = '$array[departmentId]'");
                        $orderNo = '';
                        $companyName = $department['name'];
                        break;
                    case '员工':
                        $staff = query('staff', "stid = '$array[staffId]'");
                        $orderNo = $staff['orderNo'];
                        $companyName = $staff['name'];
                        break;
                    default:
                        $orderNo = '';
                        $companyName = '';
                        break;
                }

                $targetId = match ($workFlow) {
                    '客户' => $array['khid'],
                    '供应商' => $array['supplierId'],
                    '员工' => $array['staffId'],
                    '部门' => $array['departmetnId'],
                    '存货' => $array['materialId'],
                    '现金流' => $array['cashId'],
                    '项目' => $array['projectId'],
                };
                $initResult = $obj->initMoney($workFlow, $targetId, $month,$array['subjectId']);
                $monthResult = $obj->monthBalance($workFlow, $targetId, $month, $month,$array['subjectId']);
                $balance = $obj->balance($workFlow, $targetId, $month,$array['subjectId']);
                $tr[] = [$orderNo, $companyName, $initResult['jieMoney'], $initResult['daiMoney'], $monthResult['jieMoney'], $monthResult['daiMoney'], $balance['jieMoney'], $balance['daiMoney']];
            }
        }

        if (count($tr) > 0) {
            $this->excelOut($title, $tr, $fileName, $saveDir);
            return true;
        }
        return false;
    }

    /**
     * 现金流量表
     * @param $id
     * @param $date
     * @param $url
     * @return bool|string
     */
    public function generateCash($id, $date, $url): bool|string
    {
        $company = query('company',"coid = '".self::$coid."'");
        $fileName = $company['name'].'_'.date('Y-m', strtotime($date)) . '月现金流量表.xlsx';
        $bool = $this->exportFile_cash(serverRoot . $url . '/' . $fileName, $fileName, date('Y-m', strtotime($date)));
        if ($bool) {
            $bool = static::insert(array(
                'table' => self::tableMx,
                'field' => [
                    'id' => suiji(),
                    'targetId' => $id,
                    'coid' => self::$coid,
                    'pid' => $this->folderId,
                    'type' => 'file',
                    'name' => $fileName,
                    'path' => $url . '/' . $fileName,
                    'size' => filesize(serverRoot . $url . '/' . $fileName),
                    'suffix' => 'xlsx',
                    'stid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                return '生成现金流量表失败';
            }
        }
        return true;
    }

    /**
     * 导出现金流量表
     * @param $saveDir
     * @param $fileName
     * @param $month
     * @return bool
     */
    public function exportFile_cash($saveDir, $fileName, $month): bool
    {
        $obj = new cashFlowClass();
        $assetObj = new assetDebtClass();
        $assetObj->isExport = true;
        $tr = [];
        $title = array('项目', '行次', "本年累计金额", '本期金额');

        $all = find(array('table' => 'cash', 'field' => "distinct type", 'where' => "coid = '" . self::$coid . "' and type != '' order by any_value(code)"));
        $list = 0;
        $bigNum = ['一、', '二、', '三、'];
        $cashAdd = [
            'balance' => 0,
            'monthBalance' => 0,
        ];
        foreach ($all['array'] as $index => $array) {
            $tr[] = [$bigNum[$index] . $array['type'], ' ', ' ', ' '];
            $children = find(array('table' => 'cash', 'where' => "coid = '" . self::$coid . "' and type = '$array[type]' order by code"));
            foreach ($children['array'] as $item) {
                $result = $obj->balance($month, $item['id']);
                $tr[] = [$item['name'], ++$list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];
            }
            $result = $obj->totalBalance($array['type'], $month);
            $cashAdd['balance'] += $result['balance'];
            $cashAdd['monthBalance'] += $result['monthBalance'];
            $tr[] = [$array['type'] . '净额', ++$list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];
        }
        $tr[] = ["四、现金净增加额", ++$list, $assetObj->fontColor($cashAdd['balance']), $assetObj->fontColor($cashAdd['monthBalance'])];

        $result = $obj->initPeriodBalance($month);
        $tr[] = ["加：期初现金金额", ++$list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];
        $tr[] = ["五、期末现金金额", ++$list, $assetObj->fontColor($cashAdd['balance'] + $result['balance']), $assetObj->fontColor($cashAdd['monthBalance'] + $result['monthBalance'])];

        if (count($tr) > 0) {
            $this->excelOut($title, $tr, $fileName, $saveDir);
            return true;
        }
        return false;
    }

    /**
     * 生成利润表
     * @param $id
     * @param $date
     * @param $url
     * @return bool|string
     */
    public function generateProfit($id, $date, $url): bool|string
    {
        $company = query('company',"coid = '".self::$coid."'");
        $fileName = $company['name'].'_'.date('Y-m', strtotime($date)) . '月利润表.xlsx';
        $bool = $this->exportFile_profit(serverRoot . $url . '/' . $fileName, $fileName, date('Y-m', strtotime($date)));
        if ($bool) {
            $bool = static::insert(array(
                'table' => self::tableMx,
                'field' => [
                    'id' => suiji(),
                    'targetId' => $id,
                    'coid' => self::$coid,
                    'pid' => $this->folderId,
                    'type' => 'file',
                    'name' => $fileName,
                    'path' => $url . '/' . $fileName,
                    'size' => filesize(serverRoot . $url . '/' . $fileName),
                    'suffix' => 'xlsx',
                    'stid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                return '生成利润表失败';
            }
        }
        return true;
    }

    /**
     *
     */
    public function exportFile_profit($saveDir, $fileName, $month): bool
    {
        $tr = [];
        $profitObj = new profitIncomeClass();
        $title = array('资产', '行次', "期末余额", '年初余额', '负债和所有者权益', '行次', "期末余额", '年初余额');
        $all = find(array('table' => 'profit_income', 'where' => "coid = '" . self::$coid . "' and pid = '' order by list"));
        $list = 0;
        $assetObj = new assetDebtClass();
        foreach ($all['array'] as $array) {
            $list++;
            if (!in_array($array['name'], ['营业利润', '利润总额', '净利润'])) {
                $result = $profitObj->balance($array['name'], $month);
            } else {
                $result = $profitObj->totalProfit($array['name'], $month,companyClass::returnRule(1));
            }
            $tr[] = [$array['title'], $list, $result['balance'], $result['monthBalance']];
            $assetObj->isExport = true;
            $res = $profitObj->loopTr($array['name'], $list, $month, $assetObj,true);
            $tr = array_merge($tr, $res);
        }
        if (count($tr) > 0) {
            $this->excelOut($title, $tr, $fileName, $saveDir);
            return true;
        }
        return false;
    }

    /**
     * 生成资产负债表
     */
    public function generateAssetDebt($id, $date, $url): bool|string
    {
        $company = query('company',"coid = '".self::$coid."'");
        $fileName = $company['name'].'_'.date('Y-m', strtotime($date)) . '月资产负债表.xlsx';
        $bool = $this->exportFile_assetDebt(serverRoot . $url . '/' . $fileName, $fileName, date('Y-m', strtotime($date)));
        if ($bool) {
            $bool = static::insert(array(
                'table' => self::tableMx,
                'field' => [
                    'id' => suiji(),
                    'targetId' => $id,
                    'coid' => self::$coid,
                    'pid' => $this->folderId,
                    'type' => 'file',
                    'name' => $fileName,
                    'path' => $url . '/' . $fileName,
                    'size' => filesize(serverRoot . $url . '/' . $fileName),
                    'suffix' => 'xlsx',
                    'stid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                return '生成资产负债表失败';
            }
        }
        return true;
    }

    public function exportFile_assetDebt($saveDir, $fileName, $month): bool
    {
        $assetObj = new assetDebtClass();
        $assetObj->isExport = true;
        $tr = [];
        $title = array('资产', '行次', "期末余额", '年初余额', '负债和所有者权益', '行次', "期末余额", '年初余额');
        //获取查询结果
        $result = find(array("table" => 'asset_debt', "where" => " coid = '" . self::$coid . "' and type ='流动资产' order by list"));
        //获取表头
        $addInt = 30;
        $list = 0;
        $leftBalanceTotal = [
            '流动资产' => 0,
            '非流动资产' => 0,
        ];
        $leftPreBalanceTotal = [
            '流动资产' => 0,
            '非流动资产' => 0,
        ];
        $rightBalanceTotal = [
            '流动负债' => 0,
            '非流动负债' => 0,
            '所有者权益(或股东权益)' => 0
        ];
        $rightPreBalanceTotal = [
            '流动负债' => 0,
            '非流动负债' => 0,
            '所有者权益(或股东权益)' => 0
        ];
        //获取记录
        foreach ($result['array'] as $index => $array) {
            if ($index == 0) {
                $tr[] = ["流动资产：", ' ', ' ', ' ', "流动负债：", ' ', ' ', ' '];
            }
            $list = $index + $addInt + 1;
            $right = query('asset_debt', "coid = '" . self::$coid . "' and list = $list");
            $rightName = " " . $right['name'];
            $rightBalance = $assetObj->balance($right['name'], $month);
            $rightBalanceMoney = voucherClass::zeroToEmpty($rightBalance['balance']);
            $rightPreBalanceMoney = voucherClass::zeroToEmpty($rightBalance['preBalance']);
            if ($array['name'] == '在产品') {
                $rightName = " 流动负债合计";
                $right['list'] = 41;
                $rightBalanceMoney = voucherClass::zeroToEmpty($rightBalanceTotal['流动负债']);
                $rightPreBalanceMoney = voucherClass::zeroToEmpty($rightPreBalanceTotal['流动负债']);
            }
            if ($array['name'] == '库存商品') {
                $rightName = "非流动负债：";
                $right['list'] = ' ';
                $addInt = 29;
                $rightBalanceMoney = ' ';
                $rightPreBalanceMoney=' ';
                $rightBalance['balance'] = $rightBalance['preBalance'] =0;
            }
            $leftName = $array['name'];
            if ($array['pid']) {
                $leftName = " " . ($array['name'] == '原材料' ? "其中：原材料" : $array['name']);
            }
            $leftName = " " . $leftName;
            $leftBalance = $assetObj->balance($array['name'], $month);

            $tr[] = [
                $leftName,
                $array['list'],
                voucherClass::zeroToEmpty($leftBalance['balance']),
                voucherClass::zeroToEmpty($leftBalance['preBalance']),
                $rightName,
                $right['list'],
                $rightBalanceMoney,
                $rightPreBalanceMoney,
            ];

            //合计
            if (empty($array['pid'])){
                $leftBalanceTotal[$array['type']] += $leftBalance['balance'];
                $leftPreBalanceTotal[$array['type']] += $leftBalance['preBalance'];
            }
            if ($right['type']) {
                $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
            }
            if (!isset($result['array'][$index + 1]['name'])) {
                $list = $index + $addInt + 2;
                $right = query('asset_debt', "coid = '" . self::$coid . "' and list = $list");
                $rightBalance = $assetObj->balance($right['name'], $month);
                $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                $tr[] = [
                    " " . '流动资产合计',
                    $array['list'] + 1,
                    voucherClass::zeroToEmpty($leftBalanceTotal['流动资产']),
                    voucherClass::zeroToEmpty($leftPreBalanceTotal['流动资产']),
                    " " . $right['name'],
                    $right['list'],
                    voucherClass::zeroToEmpty($rightBalance['balance']),
                    voucherClass::zeroToEmpty($rightBalance['preBalance']),
                ];
            }
        }

        $result = find(array("table" => 'asset_debt', "where" =>"coid = '" . self::$coid . "' and type ='非流动资产' order by list"));
        foreach ($result['array'] as $index => $array) {
            $right['name'] = '';
            $right['list'] = '';
            if ($index == 0) {
                $list += 1;
                $right = query('asset_debt', "coid = '" . self::$coid . "' and list = $list");
                $rightBalance = $assetObj->balance($right['name'], $month);
                $tr[] = ["非流动资产：", ' ', ' ', ' ', " " . $right['name'], $right['list'], voucherClass::zeroToEmpty($rightBalance['balance']), voucherClass::zeroToEmpty($rightBalance['preBalance'])];
                if ($right['type']) {
                    //初始化右边的合计
                    $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                    $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                }
            }
            $list += 1;
            if ($array['list'] < 18) {
                $right = query('asset_debt', "coid = '" . self::$coid . "' and list = $list");
            }
            $rightBalance = $assetObj->balance($right['name'], $month);
            $rightBalanceMoney = voucherClass::zeroToEmpty($rightBalance['balance']);
            $rightPreBalanceMoney = voucherClass::zeroToEmpty($rightBalance['preBalance']);
            $rightName = " " . $right['name'];
            if ($array['name'] == '长期债券投资') {
                $rightName = " 非流动负债合计";
                $right['list'] = 46;
                $rightBalanceMoney = voucherClass::zeroToEmpty($rightBalanceTotal['非流动负债']);
                $rightPreBalanceMoney = voucherClass::zeroToEmpty($rightPreBalanceTotal['非流动负债']);
            }
            if ($array['name'] == '长期股权投资') {
                $rightName = "负债合计";
                $right['list'] = 47;
                $rightBalanceMoney = voucherClass::zeroToEmpty($rightBalanceTotal['流动负债'] + $rightBalanceTotal['非流动负债']);
                $rightPreBalanceMoney = voucherClass::zeroToEmpty($rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['非流动负债']);
            }
            if ($array['name'] == '生产性生物资产') {
                $rightName = "所有者权益(或股东权益)：";
                $right['list'] = ' ';
            }
            if ($array['list'] >= 25) {

                $addInt = 23;
                $list = $addInt + $array['list'];
                $right = query('asset_debt', "coid = '" . self::$coid . "' and list = $list");
                $rightBalance = $assetObj->balance($right['name'], $month);
                $rightName = " " . $right['name'];
                $rightBalanceMoney = voucherClass::zeroToEmpty($rightBalance['balance']);
                $rightPreBalanceMoney = voucherClass::zeroToEmpty($rightBalance['preBalance']);
            }
            if ($right['type']) {
                //初始化右边的合计
                $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
            }
            $leftName = " " . $array['name'];
            $leftBalance = $assetObj->balance($array['name'], $month);
            if (!in_array($array['name'],['固定资产账面价值'])){
                $leftBalanceTotal[$array['type']] =$array['direction']=='+' ? $leftBalanceTotal[$array['type']]+$leftBalance['balance']:$leftBalanceTotal[$array['type']]-$leftBalance['balance'];
                $leftPreBalanceTotal[$array['type']] = $array['direction']=='+' ?$leftPreBalanceTotal[$array['type']]+$leftBalance['preBalance']:$leftPreBalanceTotal[$array['type']]-$leftBalance['preBalance'];
            }

            $tr[] = [
                $leftName,
                $array['list'],
                voucherClass::zeroToEmpty($leftBalance['balance']),
                voucherClass::zeroToEmpty($leftBalance['preBalance']),
                $rightName,
                $right['list'] ?: ' ',
                $rightBalanceMoney,
                $rightPreBalanceMoney
            ];
            if (!isset($result['array'][$index + 1]['name'])) {
                $rightBalanceMoney = voucherClass::zeroToEmpty($rightBalanceTotal['所有者权益(或股东权益)']);
                $rightPreBalanceMoney = voucherClass::zeroToEmpty($rightPreBalanceTotal['所有者权益(或股东权益)']);
                $tr[] = [
                    " " . '非流动资产合计',
                    $array['list'] + 1,
                    voucherClass::zeroToEmpty($leftBalanceTotal['非流动资产']),
                    voucherClass::zeroToEmpty($leftPreBalanceTotal['非流动资产']),
                    " " . '所有者权益(或股东权益)合计',
                    $array['list'] + $addInt + 1,
                    $rightBalanceMoney,
                    $rightPreBalanceMoney
                ];

                $tr[] = [
                    "资产总计",
                    $array['list'] + 2,
                    voucherClass::zeroToEmpty($leftBalanceTotal['流动资产'] + $leftBalanceTotal['非流动资产']),
                    voucherClass::zeroToEmpty($leftPreBalanceTotal['流动资产'] + $leftPreBalanceTotal['非流动资产']),
                    "负债和所有者权益(或股东权益)总计",
                    $array['list'] + $addInt + 2,
                    voucherClass::zeroToEmpty($rightBalanceTotal['非流动负债'] + $rightBalanceTotal['流动负债'] + $rightBalanceTotal['所有者权益(或股东权益)']),
                    voucherClass::zeroToEmpty($rightPreBalanceTotal['非流动负债'] + $rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['所有者权益(或股东权益)']),
                ];
            }
        }
        if (count($tr) > 0) {
            $this->excelOut($title, $tr, $fileName, $saveDir);
            return true;
        }
        return false;
    }

    /**
     * 生成科目余额表
     * @param $id
     * @param $date
     * @param $url
     * @return bool|string
     */
    public function generateSubjectBalance($id, $date, $url): bool|string
    {
        $company = query('company',"coid = '".self::$coid."'");
        $fileName = $company['name'].'_'.date('Y-m', strtotime($date)) . '月科目余额表.xlsx';
        $bool = $this->exportFile_subject_balance(serverRoot . $url . '/' . $fileName, $fileName, date('Y-m', strtotime($date)));
        if ($bool) {
            $bool = static::insert(array(
                'table' => self::tableMx,
                'field' => [
                    'id' => suiji(),
                    'targetId' => $id,
                    'coid' => self::$coid,
                    'pid' => $this->folderId,
                    'type' => 'file',
                    'name' => $fileName,
                    'path' => $url . '/' . $fileName,
                    'size' => filesize(serverRoot . $url . '/' . $fileName),
                    'suffix' => 'xlsx',
                    'stid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                return '生成科目余额表失败';
            }
        }
        return true;
    }

    public function exportFile_subject_balance($saveDir, $fileName, $month_date): bool
    {
        $title = array("科目编码", "科目名称", "借方期初余额", '贷方期初余额', "借方本期发生额", '贷方本期发生额', '借方期末余额', '贷方期末余额');
        $obj = new subjectBalanceClass();
        //获取查询结果
        $all = find(array(
            'table' => "subject",
            'where' => "id in (select distinct b.subjectId from voucher as a join voucher_detail as b on a.id= b.orderId where a.isTemplate = '否' and a.coid = '" . self::$coid . "' and date_format(a.recordDate,'%Y-%m') = '$month_date' ".voucherClass::joinWhere().") order by code asc"
        ));
        //获取表头
        $tr = [];
        foreach ($all['array'] as $array) {
            //期初
            $initResult = $obj->initMoney($array, $month_date);
            //本期合计
            $monthResult = $obj->monthBalance($month_date, $month_date, $array['id']);
            //期末余额
            $balanceResult = $obj->balance($month_date, $array['id']);
            $tr[] = [$array['code'], $array['name'], $initResult['jieMoney'], $initResult['daiMoney'], $monthResult['jieMoney'], $monthResult['daiMoney'], $balanceResult['jieBalance'], $balanceResult['daiBalance']];
        }
        if (count($tr) > 0) {
            $this->excelOut($title, $tr, $fileName, $saveDir);
            return true;
        }
        return false;
    }

    /**
     * 生成项目明细表
     */
    public function generateProjectDetail($id, $date, $url): bool|string
    {
        $company = query('company',"coid = '".self::$coid."'");
        $fileName = $company['name'].'_'.date('Y-m', strtotime($date)) . '月核算项目明细表.xlsx';
        $bool = $this->exportFile_project_detail(serverRoot . $url . '/' . $fileName, $fileName, date('Y-m', strtotime($date)));
        if ($bool) {
            $bool = static::insert(array(
                'table' => self::tableMx,
                'field' => [
                    'id' => suiji(),
                    'targetId' => $id,
                    'coid' => self::$coid,
                    'pid' => $this->folderId,
                    'type' => 'file',
                    'name' => $fileName,
                    'path' => $url . '/' . $fileName,
                    'size' => filesize(serverRoot . $url . '/' . $fileName),
                    'suffix' => 'xlsx',
                    'stid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                return '生成核算项目明细表失败';
            }
        }
        return true;
    }


    public function exportFile_project_detail($saveDir, $fileName, $month_date)
    {
        $projectDetail = new projectDetailsClass();
        $title = array("日期", "凭证字", "科目", '摘要', '借方', '贷方', '方向', '余额');
        $tr = [];
        $option = ['客户', '供应商', '员工', '部门', '存货', '项目', '现金流'];
        $startMonth = $month_date;
        projectDetailsClass::$isFormat = true;
        foreach ($option as $workFlow) {
            $assitAll = match ($workFlow) {
                '客户' => find(array('table'=>'kehu','field'=>"khid as targetId",'where'=>"coid = '" . self::$coid . "' order by orderNo asc")),
                '供应商' => find(array('table'=>'supplier','field'=>"id as targetId",'where'=>"coid = '" . self::$coid . "' order by code asc")),
                '员工' => find(array('table'=>'staff','field'=>"stid as targetId",'where'=>"state !='离职' order by orderNo asc")),
                '部门' =>find(array('table'=>'department','field'=>"id as targetId",'where'=>"1=1 order by orderNo asc")),
                '存货' => find(array('table'=>'material','field'=>"id as targetId",'where'=>"coid = '" . self::$coid . "' order by code asc")),
                '现金流' =>  find(array('table'=>'cash','field'=>"id as targetId",'where'=>"coid = '" . self::$coid . "' order by code asc")),
                '项目' =>  find(array('table'=>'project','field'=>"id as targetId",'where'=>"coid = '" . self::$coid . "' order by orderNo asc")),
            };
            foreach ($assitAll['array'] as $aArray){
                $assitWhere = '';
                switch ($workFlow) {
                    case '客户':
                        $assitWhere .= " and khid = '" . $aArray['targetId'] . "'";
                        break;
                    case '供应商':
                        $assitWhere .= " and supplierId = '" . $aArray['targetId'] . "'";
                        break;
                    case '员工':
                        $assitWhere .= " and staffId = '" . $aArray['targetId'] . "'";
                        break;
                    case '部门':
                        $assitWhere .= " and departmentId = '" . $aArray['targetId'] . "'";
                        break;
                    case '存货':
                        $assitWhere .= " and materialId = '" . $aArray['targetId'] . "'";
                        break;
                    case '现金流':
                        $assitWhere .= " and cashId = '" . $aArray['targetId'] . "'";
                        break;
                    case '项目':
                        $assitWhere .= " and projectId = '" . $aArray['targetId'] . "'";
                        break;
                }
                $page = find(array("table" => "subject", "where" => "coid = '" . self::$coid . "' and (id in (select distinct b.subjectId from voucher as a join voucher_detail as b on a.id = b.orderId where 1=1 ".$assitWhere.voucherClass::joinWhere().") or id in (select  id from subject_assist where orderId = id and initMoney >0 $assitWhere )) order by code asc"));

                foreach ($page['array'] as $array) {
                    $all = find(array('table' => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId", "where" => "b.subjectId = '$array[id]' and a.coid = '".self::$coid."' ".$assitWhere.voucherClass::joinWhere()." and a.isTemplate = '否' order by a.recordDate asc,a.voucherNo asc,b.list"));
                    if (is_array($all['array']) && count($all['array']) == 0) {
                        $targetId = $aArray['targetId'];

                        $result = $projectDetail->initMoney($workFlow, $targetId, $array, $startMonth);
                        $initDate = $startMonth . '-01';
                        if (empty(trim($result['jieMoney'])) && empty(trim($result['daiMoney'])) && empty(trim($result['balance']))){
                            continue;
                        }
                        $tr[] = [
                            $initDate,
                            '',
                            $array['code'] . $array['name'],
                            '期初余额',
                            $result['jieMoney'],
                            $result['daiMoney'],
                            $result['direction'],
                            $result['balance'],
                        ];
                    }
                    foreach ($all['array'] as $index => $item) {
                        $voucherWord = query('voucher_word', "id = '$item[voucherWordId]'");
                        //期初
                        if ($index == 0 || (isset($all['array'][$index - 1]['subjectId']) && $item['subjectId'] != $all['array'][$index - 1]['subjectId'])) {
                            $targetId = match ($workFlow) {
                                '客户' => $item['khid'],
                                '供应商' => $item['supplierId'],
                                '员工' => $item['staffId'],
                                '部门' => $item['departmentId'],
                                '存货' => $item['materialId'],
                                '现金流' => $item['cashId'],
                                '项目' => $item['projectId'],
                            };
                            $result = $projectDetail->initMoney($workFlow, $targetId, $array, date('Y-m', strtotime($item['recordDate'])));
                            $initDate = date('Y-m', strtotime($item['recordDate'])) . '-01';
                            $tr[] = [
                                $initDate,
                                '',
                                $array['code'] . $array['name'],
                                '期初余额',
                                $result['jieMoney'],
                                $result['daiMoney'],
                                $result['direction'],
                                $result['balance'],
                            ];
                        }
                        //中间的内容
                        $item['money'] = voucherClass::zeroToEmpty(number_format(self::centToYuan($item['money']), 2));
                        $pinzheng = $voucherWord['word'] . '-' . $item['voucherNo'];
                        if ($item['direction'] == '借') {
                            $jie = $item['money'];
                            $dai = '';
                        } else {
                            $jie = '';
                            $dai = $item['money'];
                        }
                        $targetId = match ($workFlow) {
                            '客户' => $item['khid'],
                            '供应商' => $item['supplierId'],
                            '员工' => $item['staffId'],
                            '部门' => $item['departmentId'],
                            '存货' => $item['materialId'],
                            '现金流' => $item['cashId'],
                            '项目' => $item['projectId'],
                        };
                        $result = $projectDetail->balance($item['recordDate'], $item['subjectId'], $item['voucherNo'], $workFlow, $targetId);
                        $tr[] = [
                            $item['recordDate'],
                            $pinzheng,
                            $array['code'] . $array['name'],
                            $item['summary'],
                            $jie,
                            $dai,
                            $result['direction'],
                            $result['balance'],
                        ];
                        //本期累计和本年累计
                        if ((isset($all['array'][$index + 1]['subjectId']) && ($item['subjectId'] != $all['array'][$index + 1]['subjectId'] || date('Y-m', strtotime($all['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($item['recordDate'])))) ||
                            !isset($all['array'][$index + 1]['subjectId'])
                        ) {
                            $targetId = match ($workFlow) {
                                '客户' => $item['khid'],
                                '供应商' => $item['supplierId'],
                                '员工' => $item['staffId'],
                                '部门' => $item['departmentId'],
                                '存货' => $item['materialId'],
                                '现金流' => $item['cashId'],
                                '项目' => $item['projectId'],
                            };
                            $day = sprintf("%02d", date('t', strtotime($item['recordDate'])));
                            $endMonthDate = date('Y-m-' . $day, strtotime($item['recordDate']));
                            $result = $projectDetail->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $item['subjectId']);
                            $balance = $projectDetail->balance($item['recordDate'], $item['subjectId'], '累计', $workFlow, $targetId);
                            $totalBalance = $projectDetail->monthBalance($workFlow, $targetId, date('Y-m', strtotime($item['recordDate'])), $array['id'], 'year');
                            $tr[] = [
                                $endMonthDate,
                                '',
                                $array['code'] . $array['name'],
                                '本期合计',
                                $result['jieMoney'],
                                $result['daiMoney'],
                                $balance['direction'],
                                $balance['balance'],
                            ];
                            $tr[] = [
                                $endMonthDate,
                                '',
                                $array['code'] . $array['name'],
                                '本年累计',
                                $totalBalance['jieMoney'],
                                $totalBalance['daiMoney'],
                                $balance['direction'],
                                $balance['balance'],
                            ];
                        }
                    }
                }
            }

        }
        if (count($tr) > 0) {
            $this->excelOut($title, $tr, $fileName, $saveDir);
            return true;
        }
        return false;
    }

    /**
     * 获取辅助核算名称
     * @param $targetId
     * @param $workFlow
     * @return string
     */
    public function assetName($targetId, $workFlow): string
    {
        switch ($workFlow) {
            case '客户':
                $kehu = query('kehu', "khid = '$targetId'");
                $assetName = '客户：' . $kehu['companyName'];
                break;
            case '供应商':
                $supplier = query('supplier', "id = '$targetId'");
                $assetName = '供应商：' . $supplier['name'];
                break;
            case '员工':
                $staff = query('staff', "stid = '$targetId'");
                $assetName = '员工：' . $staff['name'];
                break;
            case '部门':
                $department = query('department', "id = '$targetId'");
                $assetName = '部门：' . $department['name'];
                break;
            case '存货':
                $material = query('material', "id = '$targetId'");
                $assetName = '存货：' . $material['code'] . '-' . $material['name'] . '-' . $material['code'];
                break;
            case '现金流':
                $cash = query('cash', "id = '$targetId'");
                $assetName = '现金流：' . $cash['name'];
                break;
            case '项目':
                $project = query('project', "id = '$targetId'");
                $assetName = '项目：' . $project['name'];
                break;
            default:
                $assetName = '';
                break;
        }
        return $assetName;
    }

    /**
     * 生成总账
     */
    public function generateTotalAccount($id, $date, $url): bool|string
    {
        $company = query('company',"coid = '".self::$coid."'");
        $fileName = $company['name'].'_'.date('Y-m', strtotime($date)) . '月总账.xlsx';
        $bool = $this->exportFile_account(serverRoot . $url . '/' . $fileName, $fileName, date('Y-m', strtotime($date)));
        if ($bool) {
            $bool = static::insert(array(
                'table' => self::tableMx,
                'field' => [
                    'id' => suiji(),
                    'targetId' => $id,
                    'coid' => self::$coid,
                    'pid' => $this->folderId,
                    'type' => 'file',
                    'name' => $fileName,
                    'path' => $url . '/' . $fileName,
                    'size' => filesize(serverRoot . $url . '/' . $fileName),
                    'suffix' => 'xlsx',
                    'stid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                return '生成总账失败';
            }
        }
        return true;
    }

    public function exportFile_account($saveDir, $fileName, $month_date)
    {
        $tr = [];
        $detail = new accountDetailsClass();
        $accountTotal = new accountTotalClass();
        $title = array("科目编码", "科目名称", "期间", '摘要', '借方余额', '贷方余额');
        $all = find(array('table' => "voucher as a join voucher_detail as b on a.id= b.orderId", 'where' => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month_date' ".voucherClass::joinWhere()." order by any_value(recordDate) asc,any_value(a.voucherNo) asc,any_value(b.list)", 'field' => "distinct b.subjectId"));
        foreach ($all['array'] as $array) {
            $subject = query('subject', "id = '$array[subjectId]'");
            $start = new DateTime($month_date . '-01');
            $end = new DateTime($month_date . '-01');
            $end->modify('+1 month');
            $interval = DateInterval::createFromDateString('1 month');
            $period = new DatePeriod($start, $interval, $end);
            foreach ($period as $k => $dt) {
                foreach (accountTotalClass::typeOption as $classify) {
                    $month = $dt->format("Y年m月");
                    if ($k > 0 && $classify == '期初金额') {
                        continue;
                    }
                    switch ($classify) {
                        case '期初金额':
                            $result = $detail->initMoney($subject['id'], $dt->format("Y-m"));
                            $tr[] = [$subject['code'], $subject['name'], $month, $classify, $result['jieMoney'], $result['daiMoney'], $result['jieBalance'], $result['daiBalance']];
                            break;
                        case '本期合计':
                            $result = $detail->monthBalance($dt->format("Y-m"), $subject['id']);
                            $balance = $accountTotal->balance($dt->format("Y-m"), $subject['id']);
                            $tr[] = [$subject['code'], $subject['name'], $month, $classify, $result['jieMoney'], $result['daiMoney'], $balance['jieBalance'], $balance['daiBalance']];
                            break;
                        case '本年累计':
                            $balance = $accountTotal->balance($dt->format("Y-m"), $subject['id']);
                            $totalBalance = $detail->monthBalance($dt->format("Y-m"), $subject['id'], 'year');
                            $tr[] = [$subject['code'], $subject['name'], $month, $classify, $totalBalance['jieMoney'], $totalBalance['daiMoney'], $balance['jieBalance'], $balance['daiBalance']];
                            break;
                    }
                }
            }
        }
        if (is_array($all['array']) && count($all['array']) > 0) {
            $this->excelOut($title, $tr, $fileName, $saveDir);
            return true;
        }
        return false;
    }

    /**
     * 生成凭证
     * @param $id
     * @param $date
     * @param $url
     * @return bool|string
     */
    public function generateVoucher($id, $date, $url): bool|string
    {
        $company = query('company',"coid = '".self::$coid."'");
        $fileName = $company['name'].'_'.date('Y-m', strtotime($date)) . '月凭证.xlsx';
        $bool = $this->exportFile_voucher(serverRoot . $url . '/' . $fileName, $fileName, date('Y-m', strtotime($date)));
        if ($bool) {
            $bool = static::insert(array(
                'table' => self::tableMx,
                'field' => [
                    'id' => suiji(),
                    'targetId' => $id,
                    'coid' => self::$coid,
                    'pid' => $this->folderId,
                    'type' => 'file',
                    'name' => $fileName,
                    'path' => $url . '/' . $fileName,
                    'size' => filesize(serverRoot . $url . '/' . $fileName),
                    'suffix' => 'xlsx',
                    'stid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                return '生成凭证失败';
            }
        }
        return true;
    }

    /**
     *
     * @param $saveDir
     * @param $fileName
     * @param $month
     * @return bool
     */
    public function exportFile_voucher($saveDir, $fileName, $month): bool
    {
        $tr = [];
        $title = ["日期", "凭证号", '摘要', '科目编码', '科目名称', '币种', '借方金额', '贷方金额', '数量', '计量单位', '汇率', '外币金额', '客户名称', '供应商名称',
            '员工名称', '部门名称', '项目名称', '存货名称', '现金流名称', '制单人'];
        //获取查询结果
        $parentAll = find(array('table' => "voucher", 'where' => "coid = '" . self::$coid . "' and isTemplate = '否' and date_format(recordDate,'%Y-%m') = '$month' ".voucherClass::auditWhere()." order by voucherNo desc"));
        foreach ($parentAll['array'] as $array) {
            $voucherWord = query('voucher_word', "id = '$array[voucherWordId]'");
            $parentData = [
                $array['recordDate'],
                $voucherWord['word'] . '-' . $array['voucherNo'],
            ];
            $childAll = find(array("table" => "voucher_detail",
                "where" => " orderId = '$array[id]' order by list"));
            foreach ($childAll['array'] as $item) {
                $item['money'] = self::centToYuan($item['money']);
                $currency = query('currency', "id = '$item[currencyId]'");
                $subjectAttr = json_decode($item['subjectAttr'], true);
                if ($item['direction'] == '借') {
                    $jieMoney = $item['money'];
                    $daiMoney = '';
                } else {
                    $jieMoney = '';
                    $daiMoney = $item['money'];
                }
                $kehu = query('kehu', "khid = '$item[khid]'");
                $supplier = query('supplier', "id = '$item[supplierId]'");
                $staff = query('staff', "stid = '$item[staffId]'");
                $department = query('department', "id = '$item[departmentId]'");
                $project = query('project', "id = '$item[projectId]'");
                $mateial = query('material', "id = '$item[materialId]'");
                $cash = query('cash', "id = '$item[cashId]'");
                $tr[] = array_merge($parentData, [
                    $item['summary'],
                    $item['subjectCode'],
                    $item['subjectName'],
                    $currency['name'],
                    $jieMoney,
                    $daiMoney,
                    voucherClass::zeroToEmpty($item['voucherNum']),
                    $item['unit'],
                    voucherClass::zeroToEmpty($subjectAttr['voucherRate']),
                    voucherClass::zeroToEmpty(round($item['money'] * $subjectAttr['voucherRate'], 2)),
                    $kehu['companyName'],
                    $supplier['name'],
                    $staff['name'],
                    $department['name'],
                    $project['name'],
                    $mateial['id'] ? ($mateial['code'] . '-' . $mateial['name'] . '-' . $mateial['model']) : '',
                    $cash['name'],
                    voucherClass::findStaff($array['stid'])
                ]);
            }
        }
        if (is_array($parentAll['array']) && count($parentAll['array']) > 0) {
            $this->excelOut($title, $tr, $fileName, $saveDir);
            return true;
        }
        return false;
    }

    /**
     * 生成明细账
     * @param $id
     * @param $date
     * @param $url
     * @return bool|string
     */
    public function generateDetail($id, $date, $url): bool|string
    {
        $company = query('company',"coid = '".self::$coid."'");
        $fileName = $company['name'].'_'.date('Y-m', strtotime($date)) . '月明细账.xlsx';
        $bool = $this->exportFile_detail(serverRoot . $url . '/' . $fileName, $fileName, date('Y-m', strtotime($date)));
        if ($bool) {
            $bool = static::insert(array(
                'table' => self::tableMx,
                'field' => [
                    'id' => suiji(),
                    'targetId' => $id,
                    'coid' => self::$coid,
                    'pid' => $this->folderId,
                    'type' => 'file',
                    'name' => $fileName,
                    'path' => $url . '/' . $fileName,
                    'size' => filesize(serverRoot . $url . '/' . $fileName),
                    'suffix' => 'xlsx',
                    'stid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                return '生成明细账失败';
            }
        }
        return true;
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'name'          => [
                        'name'  => "文件名称",
                        'width' => 400,
                    ],
                    'size'  => [
                        'name'  => '大小',
                        'width' => 400,
                        'sort' => 1,
                    ],
                    'time'         => [
                        'name'  => '归档日期',
                        'width' => 400,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }


    public function detail($date)
    {
        //like查询数组
        $like = [];
        $info = query(self::table, "coid = '" . self::$coid . "' and locationDate = '$date'");
        $and = '';
        if (empty($info['id'])) {
            $and = " and 1!=1";
        }
        //全等查询数组
        $equal = array(
            "targetId" => $info['id'],//对象
            'coid' => self::$coid,
            'type' => 'file'
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::tableMx, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => array("name" => "listId", "value" => $array['id']),
                "preview" => [
                    "format" => $array['suffix'],
                    "name" => $array['name'],
                    "href" => $array['path'],
                ],
                "download" => array(
                    "type" => $array['suffix'],
                    "name" => $array['name'],
                    "href" => $array['path'],
                ),
            ];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'size':
                        $row[] = self::formatSize($array['size']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }

        //控件
        $button = "";
        if ($this->power(self::page, "archive")) {
            $button .= "<span onclick=\"layer('" . self::page . "','archive',{id:'" . $info['id'] . "',date:'" . $date . "'})\" class='spanButton'>归档</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . "<div class='flex-box p-5'>".$button."</div>" . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = '是否确认删除所选归档文件？';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word'=>$word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }
    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?: $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            $company = query('company',"coid = '".self::$coid."'");
            foreach ($array as $id) {
                $file = query(self::tableMx, " id = '$id' ");
                $info = query(self::table,"id = '$file[targetId]'");
                fileDelete($file['path']);
                //最后删除基本参数
                delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "账套【{$company['name']}】会计期间【" . $info['month'] . "】的附件【{$file['name']}】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
    /**
     * 导出明细账
     * @param $saveDir
     * @param $fileName
     * @param $month
     * @return bool
     */
    public function exportFile_detail($saveDir, $fileName, $month)
    {
        $detail = new accountDetailsClass();
        $tr = [];
        $title = array("日期", "凭证字", "科目", '摘要', '借方', '贷方', '借方余额', '贷方余额');
        $startMonth = $month;
        $initDate = $startMonth . '-01';
        //获取查询结果
        $subjectAll = find(array('table' => "voucher as a join voucher_detail as b on a.id = b.orderId", 'where' => "a.coid = '" . self::$coid . "' and a.isTemplate = '否'".voucherClass::joinWhere(), 'field' => "distinct b.subjectId"));
        foreach ($subjectAll['array'] as $item) {
            $all = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId",
                'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId",
                "where" => "a.coid = '" . self::$coid . "' and date_format(a.recordDate,'%Y-%m') = '$month' and a.isTemplate = '否' and b.subjectId ='$item[subjectId]' ".voucherClass::joinWhere()." order by recordDate asc,a.voucherNo asc,b.list"));
            $subject = query('subject', "id = '$item[subjectId]'");
            accountDetailsClass::$isFormat = true;
            $result = $detail->initMoney($item['subjectId'], $startMonth);
            $tr[] = [$initDate, '', $subject['code'] . $subject['name'], '期初余额', $result['jieMoney'], $result['daiMoney'], $result['jieBalance'], $result['daiBalance']];
            foreach ($all['array'] as $index => $array) {
                $voucher_word = query('voucher_word', "id = '$array[voucherWordId]'");
                $array['money'] = voucherClass::zeroToEmpty(number_format(self::centToYuan($array['money']), 2));
                if ($array['direction'] == '借') {
                    $jie = $array['money'];
                    $dai = '';
                } else {
                    $jie = '';
                    $dai = $array['money'];
                }
                $result = $detail->balance($array['recordDate'], $array['subjectId'], $array['voucherNo']);
                $tr[] = [$array['recordDate'], $voucher_word['word'] . '-' . $array['voucherNo'], $subject['code'] . $subject['name'], $array['summary'], $jie, $dai, $result['jieBalance'], $result['daiBalance']];
                if ((isset($page['array'][$index + 1]['subjectId']) && (date('Y-m', strtotime($page['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($array['recordDate'])))) ||
                    !isset($page['array'][$index + 1]['subjectId'])
                ) {
                    $endMonthDate = date('Y-m', strtotime($array['recordDate']));
                    $result = $detail->monthBalance(date('Y-m', strtotime($array['recordDate'])), $array['subjectId']);
                    $balance = $detail->balance($array['recordDate'], $array['subjectId'], '累计');
                    $totalBalance = $detail->monthBalance(date('Y-m', strtotime($array['recordDate'])), $subject['id'], 'year');
                    $tr[] = [$endMonthDate, '', $subject['code'] . $subject['name'], '本期合计', $result['jieMoney'], $result['daiMoney'], $balance['jieBalance'], $balance['daiBalance']];
                    $tr[] = [$endMonthDate, '', $subject['code'] . $subject['name'], '本年累计', $totalBalance['jieMoney'], $totalBalance['daiMoney'], $balance['jieBalance'], $balance['daiBalance']];
                }
            }
        }
        if (is_array($subjectAll['array']) && count($subjectAll['array']) > 0) {
            $this->excelOut($title, $tr, $fileName, $saveDir);
            return true;
        }
        return false;
    }
}
